<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Common\Http\Response;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Cache\Cache;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\PaginatorInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;
use Psr\Container\ContainerInterface;

abstract class AbstractController
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;
    /**
     * @Inject()
     * @var Cache
     */
    protected $Cache;


    /**
     * @Inject()
     * @var Response
     */
    protected $jsonResponse;


    public function getAdminId()
    {
//            公共处理获取adminid
        return ($this->request->getHeaderLine('admin_id')) ?? 0;
    }


    public function getUsername()
    {
//            公共处理获取username
        return $this->request->getHeaderLine('username');
    }

    public function getIp()
    {
//            公共处理获取ip
        return ($this->request->getServerParams()['remote_addr']) ?? 0;
    }

    /**
     * 获取分页
     * getPager
     * @return int
     * date:2021/9/15
     * time:17:07
     * auth：xyc
     */
    protected function getPager()
    {
        return (int)$this->request->query("current", 1);
    }

    /**
     * getPagerName
     * @return string
     * date:2021/9/22
     * time:14:58
     * auth：xyc
     */
    protected function getPagerName()
    {
        return "current";
    }

    /**
     * 获取分页数
     * getPager
     * @return int
     * date:2021/9/15
     * time:17:07
     * auth：xyc
     */
    protected function getPageSize()
    {
        return (int)$this->request->query("size", 10);
    }


    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * 分页
     * paginate
     * @param $obj
     * @return PaginatorInterface
     * date:2022/1/10
     * time:10:28
     * auth：xyc
     */
    protected function paginate($obj): ?PaginatorInterface
    {
        return $obj->paginate($this->getPageSize(), ['*'], $this->getPagerName(), $this->getPager());
    }


    /**
     * checkRequired
     * @param array $arr
     * @param array $fileds
     * @param array $outArr
     * @return bool
     * date:2022/1/10
     * time:14:07
     * auth：xyc
     */
    protected function checkRequired(array $arr, array $fileds, array &$outArr)
    {
        $input = [];
        foreach ($arr as $key => $item) {
            if (in_array($key, $fileds)) {
                $input[] = $key;
            }
        }
        $outArr = array_diff($fileds, $input);
        return empty($outArr);
    }


    /**
     * 判断验证规则
     * validation
     * @param array $requestParam
     * @param array $validationRule
     * @param array $message
     * date:2022/1/13
     * time:9:52
     * auth：xyc
     */
    public function validation(array $requestParam, array $validationRule, array $message = [])
    {
        $validator = $this->validationFactory->make(
            $requestParam,
            $validationRule,
            $message
        );
        //        if(isset($requestParam['pid'])){
//                //   这里行业id验证
// 不能这么用，可以在sometimes里改写
//            $validator->sometimes('pid', ["required", "integer","min:0",Rule::exists('fly_industry','id')->whereNull('deleted_at'),],
//            function($input) {
//                return $input->pid != 0;
//            });
//        }

        if ($validator->fails()) {
            throw new BusinessException(ErrorCode::SYSTEM_INVALID, implode(',', $validator->errors()->all()));
        }
    }


    /**
     * sometimes判断验证规则
     * validation
     * @param array $requestParam
     * @param array $columns  验证的数组
     * @param array $validationRule
     * @param array $message

     */
    public function sometimes(array $requestParam ,array $columns,array $validationRule, array $message = [])
    {
        $validator = $this->validationFactory->make(
            $requestParam,
            []
        );
        $validator->sometimes($columns, $validationRule, function($input) {
            return $input->games >= 100;
        });
        if ($validator->fails()) {
            throw new BusinessException(ErrorCode::SYSTEM_INVALID, implode(',', $validator->errors()->all()));
        }
    }
}
